package com.bmob.lover.ui.fragment.anniversary

import android.app.DatePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.view.View
import android.widget.DatePicker
import androidx.fragment.app.viewModels
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.theone.common.ext.logI
import com.theone.common.ext.trimAll
import com.bmob.lover.R
import com.bmob.lover.data.constant.AnniversaryConstant
import com.bmob.lover.databinding.FragmentAnniversayAddBinding
import com.bmob.lover.ui.fragment.base.BaseFragment
import com.bmob.lover.viewmodel.request.AnniversaryAddActionViewModel
import com.bmob.lover.viewmodel.state.AnniversaryAddViewModel
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.ext.qmui.setTitleWithBackBtn
import com.theone.mvvm.ext.qmui.showFailTipsDialog
import com.theone.mvvm.ext.qmui.showSingleChoiceDialog
import com.theone.mvvm.ext.qmui.showSuccessTipsExitDialog
import java.util.*

class AnniversaryAddFragment :
    BaseFragment<AnniversaryAddViewModel, FragmentAnniversayAddBinding>(),
    DatePickerDialog.OnDateSetListener {

    private val mAddAction: AnniversaryAddActionViewModel by viewModels()

    override fun initView(root: View) {
        getTopBar()?.run {
            setTitleWithBackBtn("添加纪念日", this@AnniversaryAddFragment)
        }
    }

    override fun createObserver() {
        addLoadingObserve(mAddAction)
        addFailTipsObserve(mAddAction)
        mAddAction.getObjectSuccessLiveDate().observe(this) {
            mEventVm.onPublishSuccess("Anniversary")
            showSuccessTipsExitDialog("添加成功")
        }
    }

    override fun getBindingClick(): Any? = ProxyClick()


    inner class ProxyClick  {

        fun save() {
            with(getViewModel()) {
                val n = name.get().trimAll()
                n.logI()
                when {
                    n.isEmpty() -> showFailTipsDialog("名称不能为空")
                    else -> mAddAction.save(n, date.get(), type.get())
                }
            }

        }

        fun selectDate() {
            val calendar: Calendar = Calendar.getInstance()
            val dialog = DatePickerDialog(
                mActivity, this@AnniversaryAddFragment,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            dialog.show()
        }

        fun category() {
            context?.showSingleChoiceDialog(
                null, AnniversaryConstant.TYPE_ITEMS, getViewModel().type.get()
            ) { dialog, which ->
                dialog.dismiss()
                getViewModel().type.set(which)
            }
        }

    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        getViewModel().date.set("$year-${month + 1}-$dayOfMonth")
    }

}